<?php

header("Content-Type: text/html;charset=utf-8");

require_once(DIR_CATALOG_APPLICATION.'controller/rest/sms.php');

class ControllerCustomerCustomer extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('customer/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('customer/customer');

		$this->getList();
	}

	public function add() {
		$this->load->language('customer/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('customer/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {

			$customer_id = $this->model_customer_customer->addCustomer($this->request->post);
			$now_date = date('Y-m-d');
			if($this->request->post['need_review'] == false && $now_date != '2017-08-23'){
				$this->addNewCoupon($customer_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_company_name'])) {
				$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_logcenter_id'])) {
				$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_need_review'])) {
				$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
			}
			if (isset($this->request->get['filter_is_shelf_customer'])) {
				$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
			}

			if (isset($this->request->get['filter_is_magfin'])) {
				$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
			}

			if (isset($this->request->get['filter_telephone'])) {
				$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function edit() {

		$this->load->language('customer/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('customer/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			// var_dump($this->request->post);die();
			$this->model_customer_customer->editCustomer($this->request->get['customer_id'], $this->request->post);

			//判断是否发送优惠券
			$now_date = date('Y-m-d');
			$sendnew = $this->model_customer_customer->getSendNew($this->request->get['customer_id']);
			if($this->request->post['need_review'] == false && $sendnew == 0 && $now_date != '2017-08-23'){
				$this->addNewCoupon($this->request->get['customer_id']);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_company_name'])) {
				$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_logcenter_id'])) {
				$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_need_review'])) {
				$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
			}
			if (isset($this->request->get['filter_is_shelf_customer'])) {
				$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
			}


			if (isset($this->request->get['filter_is_magfin'])) {
				$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
			}

			if (isset($this->request->get['filter_telephone'])) {
				$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('customer/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('customer/customer');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $customer_id) {
				$this->model_customer_customer->deleteCustomer($customer_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_company_name'])) {
				$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_logcenter_id'])) {
				$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_need_review'])) {
				$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
			}
			if (isset($this->request->get['filter_is_shelf_customer'])) {
				$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
			}

			if (isset($this->request->get['filter_is_magfin'])) {
				$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
			}

			if (isset($this->request->get['filter_telephone'])) {
				$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	public function approve() {
		$this->load->language('customer/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('customer/customer');

		$customers = array();

		if (isset($this->request->post['selected'])) {
			$customers = $this->request->post['selected'];
		} elseif (isset($this->request->get['customer_id'])) {
			$customers[] = $this->request->get['customer_id'];
		}

		if ($customers && $this->validateApprove()) {
			$this->model_customer_customer->approve($this->request->get['customer_id']);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_company_name'])) {
				$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_logcenter_id'])) {
				$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_need_review'])) {
				$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
			}
			if (isset($this->request->get['filter_is_shelf_customer'])) {
				$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
			}

			if (isset($this->request->get['filter_is_magfin'])) {
				$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
			}

			if (isset($this->request->get['filter_telephone'])) {
				$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	public function unlock() {
		$this->load->language('customer/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('customer/customer');

		if (isset($this->request->get['email']) && $this->validateUnlock()) {
			$this->model_customer_customer->deleteLoginAttempts($this->request->get['email']);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_company_name'])) {
				$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_logcenter_id'])) {
				$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_need_review'])) {
				$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
			}
			if (isset($this->request->get['filter_is_shelf_customer'])) {
				$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
			}

			if (isset($this->request->get['filter_is_magfin'])) {
				$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
			}

			if (isset($this->request->get['filter_telephone'])) {
				$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	protected function getList() {
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_email'])) {
			$filter_email = $this->request->get['filter_email'];
		} else {
			$filter_email = null;
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$filter_recommended_code = $this->request->get['filter_recommended_code'];
		} else {
			$filter_recommended_code = null;
		}

		if (isset($this->request->get['filter_company_name'])) {
			$filter_company_name = $this->request->get['filter_company_name'];
		} else {
			$filter_company_name = null;
		}

		if (isset($this->request->get['filter_customer_group_id'])) {
			$filter_customer_group_id = $this->request->get['filter_customer_group_id'];
		} else {
			$filter_customer_group_id = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = null;
		}

		if (isset($this->request->get['filter_logcenter_id'])) {
			$filter_logcenter_id = $this->request->get['filter_logcenter_id'];
		} else {
			$filter_logcenter_id = null;
		}

		if (isset($this->request->get['filter_approved'])) {
			$filter_approved = $this->request->get['filter_approved'];
		} else {
			$filter_approved = null;
		}

		if (isset($this->request->get['filter_need_review'])) {
			$filter_need_review = $this->request->get['filter_need_review'];
		} else {
			$filter_need_review = null;
		}

		if (isset($this->request->get['filter_is_shelf_customer'])) {
			$filter_is_shelf_customer = $this->request->get['filter_is_shelf_customer'];
		} else {
			$filter_is_shelf_customer = null;
		}

		if (isset($this->request->get['filter_is_magfin'])) {
			$filter_is_magfin = $this->request->get['filter_is_magfin'];
		} else {
			$filter_is_magfin = null;
		}

		if (isset($this->request->get['filter_telephone'])) {
			$filter_telephone = $this->request->get['filter_telephone'];
		} else {
			$filter_telephone = null;
		}

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['filter_order_sum'])) {
			$filter_order_sum = $this->request->get['filter_order_sum'];
		} else {
			$filter_order_sum = null;
		}

		if (isset($this->request->get['filter_last_date_start'])) {
			$filter_last_date_start = $this->request->get['filter_last_date_start'];
		} else {
			$filter_last_date_start = null;
		}

		if (isset($this->request->get['filter_last_date_end'])) {
			$filter_last_date_end = $this->request->get['filter_last_date_end'];
		} else {
			$filter_last_date_end = null;
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'name';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_company_name'])) {
			$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$url .= '&filter_recommended_code=' . urlencode(html_entity_decode($this->request->get['filter_recommended_code'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_customer_group_id'])) {
			$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_logcenter_id'])) {
			$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
		}

		if (isset($this->request->get['filter_approved'])) {
			$url .= '&filter_approved=' . $this->request->get['filter_approved'];
		}

		if (isset($this->request->get['filter_need_review'])) {
			$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
		}

		if (isset($this->request->get['filter_is_shelf_customer'])) {
			$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
		}

		if (isset($this->request->get['filter_is_magfin'])) {
			$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
		}

		if (isset($this->request->get['filter_telephone'])) {
			$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
		}

		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . $this->request->get['filter_date_start'];
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . $this->request->get['filter_date_end'];
		}

		if (isset($this->request->get['filter_order_sum'])) {
			$url .= '&filter_order_sum=' . $this->request->get['filter_order_sum'];
		}

		if (isset($this->request->get['filter_last_date_start'])) {
			$url .= '&filter_last_date_start=' . $this->request->get['filter_last_date_start'];
		}

		if (isset($this->request->get['filter_last_date_end'])) {
			$url .= '&filter_last_date_end=' . $this->request->get['filter_last_date_end'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['add'] = $this->url->link('customer/customer/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['delete'] = $this->url->link('customer/customer/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$data['customers'] = array();
		// $data['is_shelf_customer_arr'] = array(
		// 	2=>'',
		// 	0=>'普通客户',
		// 	1=>'货架客户',
		// 	);


		$filter_data = array(
			'filter_company_name'      => $filter_company_name,
			'filter_name'              => $filter_name,
			'filter_email'             => $filter_email,
			'filter_recommended_code'  =>$filter_recommended_code,
			'filter_customer_group_id' => $filter_customer_group_id,
			'filter_status'            => $filter_status,
			'filter_logcenter_id'      => $filter_logcenter_id,
			'filter_approved'          => $filter_approved,
			'filter_need_review'       => $filter_need_review,
			'filter_is_shelf_customer'       => $filter_is_shelf_customer,
			'filter_is_magfin'         => $filter_is_magfin,
			'filter_date_start'        => $filter_date_start,
			'filter_date_end'          => $filter_date_end,
			'filter_order_sum'         => $filter_order_sum,
			'filter_last_date_start'   => $filter_last_date_start,
			'filter_last_date_end'     => $filter_last_date_end,
			'filter_telephone'         => $filter_telephone,
			'sort'                     => $sort,
			'order'                    => $order,
			'start'                    => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'                    => $this->config->get('config_limit_admin')
		);

		//Liqn 获取物流营销中心列表
		$this->load->model('catalog/logcenter');
		$data['logcenters'] = $this->model_catalog_logcenter->getLogcenters();
		//print_r($data);
		$logcenters = array();
		foreach ($data['logcenters'] as $logcenter) {
			$logcenters[$logcenter['logcenter_id']] = $logcenter['logcenter_name'];
		}
		//print_r($logcenters);
		$customer_total = $this->model_customer_customer->getTotalCustomers($filter_data);

		$results = $this->model_customer_customer->getCustomers($filter_data);
		//print_r($results);
		foreach ($results as $result) {
			if (!$result['approved']) {
				$approve = $this->url->link('customer/customer/approve', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL');
			} else {
				$approve = '';
			}

			$login_info = $this->model_customer_customer->getTotalLoginAttempts($result['email']);

			if ($login_info && $login_info['total'] >= $this->config->get('config_login_attempts')) {
				$unlock = $this->url->link('customer/customer/unlock', 'token=' . $this->session->data['token'] . '&email=' . $result['email'] . $url, 'SSL');
			} else {
				$unlock = '';
			}

			//print_r($result['is_shelf_customer']);
			$data['customers'][] = array(
				'customer_id'    => $result['customer_id'],
				'company_name'   => $result['company_name'],
				'name'           => $result['fullname'],
				'email'          => $result['email'],
				'customer_group' => $result['customer_group'],
				'status'         => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
				'need_review'    => ($result['need_review'] ? $this->language->get('text_yes') : $this->language->get('text_no')),
				'is_magfin'    => ($result['is_magfin'] ? $this->language->get('text_yes') : $this->language->get('text_no')),
				'has_license_image'    => ($result['license_image_code'] ? '已上传' : '未上传'),
				'telephone'      => $result['telephone'],
				'logcenter'      => isset($logcenters[$result['logcenter_id']])?$logcenters[$result['logcenter_id']]:'未分配',
				'order_sum'      => intval($result['order_sum']),
				'last_order_date'=> $result['last_order_date'],
				'recommended_code'          => $result['recommended_code'],
				'date_added'     => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
				'approve'        => $approve,
				'unlock'         => $unlock,
				'is_shelf_customer'         => $result['is_shelf_customer']?'货架客户':'普通客户',
				'edit'           => $this->url->link('customer/customer/edit', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL')
			);

		}

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_list'] = $this->language->get('text_list');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');
		$data['text_yes'] = $this->language->get('text_yes');
		$data['text_no'] = $this->language->get('text_no');
		$data['text_default'] = $this->language->get('text_default');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');

		$data['column_name'] = $this->language->get('column_name');
		$data['column_company_name'] = $this->language->get('column_company_name');
		$data['column_email'] = $this->language->get('column_email');
		$data['column_customer_group'] = $this->language->get('column_customer_group');
		$data['column_status'] = $this->language->get('column_status');
		$data['column_approved'] = $this->language->get('column_approved');
		$data['column_need_review'] = $this->language->get('column_need_review');
		$data['column_is_magfin'] = $this->language->get('column_is_magfin');
		$data['column_telephone'] = $this->language->get('column_telephone');
		$data['column_logcenter_id'] = $this->language->get('column_logcenter_id');
		$data['column_recommended_code'] = $this->language->get('column_recommended_code');
		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_action'] = $this->language->get('column_action');

		$data['entry_company_name'] = $this->language->get('entry_company_name');
		$data['entry_name'] = $this->language->get('entry_name');
		$data['entry_email'] = $this->language->get('entry_email');
		$data['entry_customer_group'] = $this->language->get('entry_customer_group');
		$data['entry_status'] = $this->language->get('entry_status');
		$data['entry_approved'] = $this->language->get('entry_approved');
		$data['entry_need_review'] = $this->language->get('entry_need_review');
		$data['entry_is_magfin'] = $this->language->get('entry_is_magfin');
		$data['entry_telephone'] = $this->language->get('entry_telephone');
		$data['entry_date_start'] = $this->language->get('entry_date_start');
		$data['entry_date_end'] = $this->language->get('entry_date_end');
		$data['entry_recommended_code'] = $this->language->get('entry_recommended_code');
		$data['entry_logcenter_id'] = $this->language->get('entry_logcenter_id');

		$data['button_approve'] = $this->language->get('button_approve');
		$data['button_add'] = $this->language->get('button_add');
		$data['button_edit'] = $this->language->get('button_edit');
		$data['button_delete'] = $this->language->get('button_delete');
		$data['button_filter'] = $this->language->get('button_filter');
		$data['button_login'] = $this->language->get('button_login');
		$data['button_unlock'] = $this->language->get('button_unlock');

		$data['token'] = $this->session->data['token'];

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_company_name'])) {
			$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_customer_group_id'])) {
			$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_logcenter_id'])) {
			$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
		}

		if (isset($this->request->get['filter_approved'])) {
			$url .= '&filter_approved=' . $this->request->get['filter_approved'];
		}


		if (isset($this->request->get['filter_need_review'])) {
			$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
		}
		if (isset($this->request->get['filter_is_shelf_customer'])) {
			$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
		}


		if (isset($this->request->get['filter_is_magfin'])) {
			$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
		}

		if (isset($this->request->get['filter_telephone'])) {
			$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['filter_order_sum'])) {
			$url .= '&filter_order_sum=' . $this->request->get['filter_order_sum'];
		}

		if (isset($this->request->get['filter_last_date_start'])) {
			$url .= '&filter_last_date_start=' . $this->request->get['filter_last_date_start'];
		}

		if (isset($this->request->get['filter_last_date_end'])) {
			$url .= '&filter_last_date_end=' . $this->request->get['filter_last_date_end'];
		}

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_company_name'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=company_name' . $url, 'SSL');
		$data['sort_name'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');
		$data['sort_email'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=c.email' . $url, 'SSL');
		$data['sort_customer_group'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=customer_group' . $url, 'SSL');
		$data['sort_status'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '
			&sort=c.status' . $url, 'SSL');
		$data['sort_logcenter_id'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '
			&sort=c.logcenter_id' . $url, 'SSL');
		$data['sort_order_sum'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=order_sum' . $url, 'SSL');
		$data['sort_last_order_date'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=last_order_date' . $url, 'SSL');
		$data['sort_need_review'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=c.need_review' . $url, 'SSL');
		$data['sort_telephone'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=c.telephone' . $url, 'SSL');
		$data['sort_date_added'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&sort=c.date_added' . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_company_name'])) {
			$url .= '&filter_company_name=' . urlencode(html_entity_decode($this->request->get['filter_company_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_customer_group_id'])) {
			$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_logcenter_id'])) {
			$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
		}

		if (isset($this->request->get['filter_approved'])) {
			$url .= '&filter_approved=' . $this->request->get['filter_approved'];
		}

		if (isset($this->request->get['filter_need_review'])) {
			$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
		}
		if (isset($this->request->get['filter_is_shelf_customer'])) {
			$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
		}
		if (isset($this->request->get['filter_is_magfin'])) {
			$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
		}

		if (isset($this->request->get['filter_telephone'])) {
			$url .= '&filter_telephone=' . $this->request->get['filter_telephone'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['filter_order_sum'])) {
			$url .= '&filter_order_sum=' . $this->request->get['filter_order_sum'];
		}

		if (isset($this->request->get['filter_last_date_start'])) {
			$url .= '&filter_last_date_start=' . $this->request->get['filter_last_date_start'];
		}

		if (isset($this->request->get['filter_last_date_end'])) {
			$url .= '&filter_last_date_end=' . $this->request->get['filter_last_date_end'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $customer_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($customer_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($customer_total - $this->config->get('config_limit_admin'))) ? $customer_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $customer_total, ceil($customer_total / $this->config->get('config_limit_admin')));

		$data['filter_company_name'] = $filter_company_name;
		$data['filter_name'] = $filter_name;
		$data['filter_email'] = $filter_email;
		$data['filter_customer_group_id'] = $filter_customer_group_id;
		$data['filter_status'] = $filter_status;
		$data['filter_logcenter_id'] = $filter_logcenter_id;
		$data['filter_approved'] = $filter_approved;
		$data['filter_need_review'] = $filter_need_review;
		$data['filter_is_shelf_customer'] = $filter_is_shelf_customer;
		$data['filter_is_magfin'] = $filter_is_magfin;
		$data['filter_telephone'] = $filter_telephone;
		$data['filter_date_start'] = $filter_date_start;
		$data['filter_date_end'] = $filter_date_end;
		$data['filter_order_sum'] = $filter_order_sum;
		$data['filter_last_date_start'] = $filter_last_date_start;
		$data['filter_last_date_end'] = $filter_last_date_end;

		$this->load->model('customer/customer_group');

		$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();

		$this->load->model('setting/store');

		$data['stores'] = $this->model_setting_store->getStores();

		$data['sort'] = $sort;
		$data['order'] = $order;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('customer/customer_list.tpl', $data));
	}

	protected function getForm() {
		$user_id = $this->user->getId();
		$data['user_id'] = $user_id;
		// var_dump($data['user_id']);
		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_form'] = !isset($this->request->get['customer_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');
		$data['text_yes'] = $this->language->get('text_yes');
		$data['text_no'] = $this->language->get('text_no');
		$data['text_select'] = $this->language->get('text_select');
		$data['text_none'] = $this->language->get('text_none');
		$data['text_loading'] = $this->language->get('text_loading');
		$data['text_add_ban_ip'] = $this->language->get('text_add_ban_ip');
		$data['text_remove_ban_ip'] = $this->language->get('text_remove_ban_ip');

		$data['entry_customer_group'] = $this->language->get('entry_customer_group');
		$data['entry_fullname'] = $this->language->get('entry_fullname');
		$data['entry_email'] = $this->language->get('entry_email');
		$data['entry_telephone'] = $this->language->get('entry_telephone');
		$data['entry_fax'] = $this->language->get('entry_fax');
		$data['entry_password'] = $this->language->get('entry_password');
		$data['entry_confirm'] = $this->language->get('entry_confirm');
		$data['entry_newsletter'] = $this->language->get('entry_newsletter');
		$data['entry_status'] = $this->language->get('entry_status');
		$data['entry_approved'] = $this->language->get('entry_approved');
		$data['entry_need_review'] = $this->language->get('entry_need_review');
		$data['entry_is_magfin'] = $this->language->get('entry_is_magfin');
		$data['entry_safe'] = $this->language->get('entry_safe');
		$data['entry_company'] = $this->language->get('entry_company');
		$data['entry_address'] = $this->language->get('entry_address');
		$data['entry_city'] = $this->language->get('entry_city');
		$data['entry_postcode'] = $this->language->get('entry_postcode');
		$data['entry_zone'] = $this->language->get('entry_zone');
		$data['entry_country'] = $this->language->get('entry_country');
		$data['entry_default'] = $this->language->get('entry_default');
		$data['entry_comment'] = $this->language->get('entry_comment');
		$data['entry_description'] = $this->language->get('entry_description');
		$data['entry_points'] = $this->language->get('entry_points');
		$data['entry_shipping_telephone'] = $this->language->get('entry_shipping_telephone');
		$data['entry_company_name'] = $this->language->get('entry_company_name');
		$data['entry_logcenter_id'] = $this->language->get('entry_logcenter_id');
		$data['entry_license_image'] = $this->language->get('entry_license_image');

		/*账户余额*/
		$data['entry_balance'] = $this->language->get('entry_balance');
		$data['entry_amount'] = $this->language->get('entry_amount');
		/*账户余额*/

		$data['help_safe'] = $this->language->get('help_safe');
		$data['help_points'] = $this->language->get('help_points');

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['button_address_add'] = $this->language->get('button_address_add');
		$data['button_history_add'] = $this->language->get('button_history_add');
		$data['button_transaction_add'] = $this->language->get('button_transaction_add');
		$data['button_reward_add'] = $this->language->get('button_reward_add');
		$data['button_remove'] = $this->language->get('button_remove');
		$data['button_upload'] = $this->language->get('button_upload');

		$data['tab_general'] = $this->language->get('tab_general');
		$data['tab_address'] = $this->language->get('tab_address');
		$data['tab_history'] = $this->language->get('tab_history');
		$data['tab_transaction'] = $this->language->get('tab_transaction');
		$data['tab_reward'] = $this->language->get('tab_reward');
		$data['tab_ip'] = $this->language->get('tab_ip');

		$data['token'] = $this->session->data['token'];

		if (isset($this->request->get['customer_id'])) {
			$data['customer_id'] = $this->request->get['customer_id'];
		} else {
			$data['customer_id'] = 0;
		}

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['fullname'])) {
			$data['error_fullname'] = $this->error['fullname'];
		} else {
			$data['error_fullname'] = '';
		}

		if (isset($this->error['email'])) {
			$data['error_email'] = $this->error['email'];
		} else {
			$data['error_email'] = '';
		}

		if (isset($this->error['telephone'])) {
			$data['error_telephone'] = $this->error['telephone'];
		} else {
			$data['error_telephone'] = '';
		}

		if (isset($this->error['password'])) {
			$data['error_password'] = $this->error['password'];
		} else {
			$data['error_password'] = '';
		}

		if (isset($this->error['confirm'])) {
			$data['error_confirm'] = $this->error['confirm'];
		} else {
			$data['error_confirm'] = '';
		}

		if (isset($this->error['custom_field'])) {
			$data['error_custom_field'] = $this->error['custom_field'];
		} else {
			$data['error_custom_field'] = array();
		}

		if (isset($this->error['address'])) {
			$data['error_address'] = $this->error['address'];
		} else {
			$data['error_address'] = array();
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_customer_group_id'])) {
			$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_logcenter_id'])) {
			$url .= '&filter_logcenter_id=' . $this->request->get['filter_logcenter_id'];
		}

		if (isset($this->request->get['filter_approved'])) {
			$url .= '&filter_approved=' . $this->request->get['filter_approved'];
		}

		if (isset($this->request->get['filter_need_review'])) {
			$url .= '&filter_need_review=' . $this->request->get['filter_need_review'];
		}

		if (isset($this->request->get['filter_is_shelf_customer'])) {
			$url .= '&filter_is_shelf_customer=' . $this->request->get['filter_is_shelf_customer'];
		}

		if (isset($this->request->get['filter_is_magfin'])) {
			$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
		}

		if (isset($this->request->get['filter_is_magfin'])) {
			$url .= '&filter_is_magfin=' . $this->request->get['filter_is_magfin'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		if (!isset($this->request->get['customer_id'])) {
			$data['action'] = $this->url->link('customer/customer/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		} else {
			$data['action'] = $this->url->link('customer/customer/edit', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . $url, 'SSL');
		}

		$data['cancel'] = $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, 'SSL');

		if (isset($this->request->get['customer_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$customer_info = $this->model_customer_customer->getCustomer($this->request->get['customer_id']);
			$customer_images = $this->model_customer_customer->getCustomerImages($this->request->get['customer_id']);
			$base_url = HTTP_CATALOG;
      foreach ($customer_images as $key => $ci) {
        $img_url = $base_url . 'system/storage/upload/' . $ci['filename'];
        $customer_images[$key]['img_url'] = $img_url;
      }
		}

		$this->load->model('customer/customer_group');

		$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();
		

		$data['is_buys'] = array(
			'1'=>'可以',
			'0'=>'不可以',
		);

		$data['is_alls'] = array(
			'1'=>'可以',
			'0'=>'不可以',
		);
		

		if (isset($this->request->post['customer_group_id'])) {
			$data['customer_group_id'] = $this->request->post['customer_group_id'];
		} elseif (!empty($customer_info)) {
			$data['customer_group_id'] = $customer_info['customer_group_id'];
		} else {
			$data['customer_group_id'] = $this->config->get('config_customer_group_id');
		}

		if (isset($this->request->post['is_buy'])) {
			$data['is_buy'] = $this->request->post['is_buy'];
		} elseif (!empty($customer_info)) {
			$data['is_buy'] = $customer_info['is_buy'];
		} else {
			$data['is_buy'] = 1;
		}

		if (isset($this->request->post['is_all'])) {
			$data['is_all'] = $this->request->post['is_all'];
		} elseif (!empty($customer_info)) {
			$data['is_all'] = $customer_info['is_all'];
		} else {
			$data['is_all'] = 1;
		}

		if (isset($this->request->post['fullname'])) {
			$data['fullname'] = $this->request->post['fullname'];
		} elseif (!empty($customer_info)) {
			$data['fullname'] = $customer_info['fullname'];
		} else {
			$data['fullname'] = '';
		}

		if (isset($this->request->post['email'])) {
			$data['email'] = $this->request->post['email'];
		} elseif (!empty($customer_info)) {
			$data['email'] = $customer_info['email'];
		} else {
			$data['email'] = '';
		}

		if (isset($this->request->post['telephone'])) {
			$data['telephone'] = $this->request->post['telephone'];
		} elseif (!empty($customer_info)) {
			$data['telephone'] = $customer_info['telephone'];
		} else {
			$data['telephone'] = '';
		}

		if (isset($this->request->post['fax'])) {
			$data['fax'] = $this->request->post['fax'];
		} elseif (!empty($customer_info)) {
			$data['fax'] = $customer_info['fax'];
		} else {
			$data['fax'] = '';
		}

		if (isset($this->request->post['sales_id'])) {
			$data['sales_id'] = $this->request->post['sales_id'];
		} elseif (!empty($customer_info)) {
			$data['sales_id'] = $customer_info['user_id'];
		} else {
			$data['sales_id'] = '';
		}

		if (isset($this->request->post['sales_id'])) {
			$data['sales_id_name'] = $this->request->post['sales_id_name'];
		} elseif (!empty($customer_info)) {
			$data['sales_id_name'] = $customer_info['user_name'];
		} else {
			$data['sales_id_name'] = '';
		}

		if (isset($this->request->post['company_name'])) {
			$data['company_name'] = $this->request->post['company_name'];
		} elseif (!empty($customer_info)) {
			$data['company_name'] = $customer_info['company_name'];
		} else {
			$data['company_name'] = '';
		}

		if (isset($this->request->post['logcenter_id'])) {
			$data['logcenter_id'] = $this->request->post['logcenter_id'];
		} elseif (!empty($customer_info)) {
			$data['logcenter_id'] = $customer_info['logcenter_id'];
		} else {
			$data['logcenter_id'] = '';
		}

		if (isset($this->request->post['shop_type'])) {
			$data['shop_type'] = $this->request->post['shop_type'];
		} elseif (!empty($customer_info)) {
			$data['shop_type'] = $customer_info['shop_type'];
		} else {
			$data['shop_type'] = '';
		}

    if(!empty($customer_images)) {
    	$data['customer_images'] = $customer_images;
    }
		// Custom Fields
		$this->load->model('customer/custom_field');

		$data['custom_fields'] = array();

		$filter_data = array(
			'sort'  => 'cf.sort_order',
			'order' => 'ASC'
		);

		$custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);

		foreach ($custom_fields as $custom_field) {
			$data['custom_fields'][] = array(
				'custom_field_id'    => $custom_field['custom_field_id'],
				'custom_field_value' => $this->model_customer_custom_field->getCustomFieldValues($custom_field['custom_field_id']),
				'name'               => $custom_field['name'],
				'value'              => $custom_field['value'],
				'type'               => $custom_field['type'],
				'location'           => $custom_field['location'],
				'sort_order'         => $custom_field['sort_order']
			);
		}

		if (isset($this->request->post['custom_field'])) {
			$data['account_custom_field'] = $this->request->post['custom_field'];
		} elseif (!empty($customer_info)) {
			$data['account_custom_field'] = json_decode($customer_info['custom_field'], true);
		} else {
			$data['account_custom_field'] = array();
		}

		if (isset($this->request->post['newsletter'])) {
			$data['newsletter'] = $this->request->post['newsletter'];
		} elseif (!empty($customer_info)) {
			$data['newsletter'] = $customer_info['newsletter'];
		} else {
			$data['newsletter'] = '';
		}

		if (isset($this->request->post['status'])) {
			$data['status'] = $this->request->post['status'];
		} elseif (!empty($customer_info)) {
			$data['status'] = $customer_info['status'];
		} else {
			$data['status'] = true;
		}

		if (isset($this->request->post['approved'])) {
			$data['approved'] = $this->request->post['approved'];
		} elseif (!empty($customer_info)) {
			$data['approved'] = $customer_info['approved'];
		} else {
			$data['approved'] = true;
		}


		if (isset($this->request->post['need_review'])) {
			$data['need_review'] = $this->request->post['need_review'];
		} elseif (!empty($customer_info)) {
			$data['need_review'] = $customer_info['need_review'];
 		} else {
			$data['need_review'] = true;
		}

		if (isset($this->request->post['is_shelf_customer'])) {
			$data['is_shelf_customer'] = $this->request->post['is_shelf_customer'];
		} elseif (!empty($customer_info)) {
			$data['is_shelf_customer'] = $customer_info['is_shelf_customer'];
 		} else {
			$data['is_shelf_customer'] = true;
		}
		if (isset($this->request->post['is_magfin'])) {
			$data['is_magfin'] = $this->request->post['is_magfin'];
		} elseif (!empty($customer_info)) {
			$data['is_magfin'] = $customer_info['is_magfin'];
		} else {
			$data['is_magfin'] = true;
		}

		if (isset($this->request->post['safe'])) {
			$data['safe'] = $this->request->post['safe'];
		} elseif (!empty($customer_info)) {
			$data['safe'] = $customer_info['safe'];
		} else {
			$data['safe'] = 0;
		}

		if (isset($this->request->post['password'])) {
			$data['password'] = $this->request->post['password'];
		} else {
			$data['password'] = '';
		}

		if (isset($this->request->post['confirm'])) {
			$data['confirm'] = $this->request->post['confirm'];
		} else {
			$data['confirm'] = '';
		}

		//Liqn 获取物流营销中心列表
		$this->load->model('catalog/logcenter');
		//$data['logcenters'] = $this->model_catalog_logcenter->getLogcenters();
        $data['logcenters'] = $this->model_catalog_logcenter->getAvailableLogcenters();

		$this->load->model('localisation/country');

		$data['countries'] = $this->model_localisation_country->getCountries();

		if (isset($this->request->post['address'])) {
			$data['addresses'] = $this->request->post['address'];
		} elseif (isset($this->request->get['customer_id'])) {
			$data['addresses'] = $this->model_customer_customer->getAddresses($this->request->get['customer_id']);
		} else {
			$data['addresses'] = array();
		}

		if (isset($this->request->post['address_id'])) {
			$data['address_id'] = $this->request->post['address_id'];
		} elseif (!empty($customer_info)) {
			$data['address_id'] = $customer_info['address_id'];
		} else {
			$data['address_id'] = '';
		}

		if (isset($this->request->post['recommended_code'])) {
			$data['recommended_code'] = $this->request->post['recommended_code'];
		} elseif (!empty($customer_info)) {
			$data['recommended_code'] = $customer_info['recommended_code'];
		} else {
			$data['recommended_code'] = '';
		}

		/*余额*/
		if (!empty($customer_info)) {
			$data['balance'] = $customer_info['balance'];
		} else {
			$data['balance'] = '';
		}
		/*余额*/

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('customer/customer_form.tpl', $data));
	}

	protected function validateForm() {

		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (empty($this->request->post['sales_id'])) {
			$this->error['warning'] = "必须填写正确的业务员";
		}else{
			$is_have_user = M('user')->where('user_id='.$this->request->post['sales_id'])->find();
			if(!$is_have_user){
				$this->error['warning'] = "必须填写正确的业务员";
			}
		}



		if ((utf8_strlen($this->request->post['fullname']) < 1) || (utf8_strlen(trim($this->request->post['fullname'])) > 32)) {
			$this->error['fullname'] = $this->language->get('error_fullname');
		}

		// if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $this->request->post['email'])) {
		// 	$this->error['email'] = $this->language->get('error_email');
		// }

		$customer_info = $this->model_customer_customer->getCustomerByEmail($this->request->post['email']);

		if (!isset($this->request->get['customer_id'])) {
			if ($customer_info) {
				$this->error['warning'] = $this->language->get('error_exists');
			}
		} else {
			if ($customer_info && ($this->request->get['customer_id'] != $customer_info['customer_id'])) {
				$this->error['warning'] = $this->language->get('error_exists');
			}
		}

		if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
			$this->error['telephone'] = $this->language->get('error_telephone');
		}

		// Custom field validation
		$this->load->model('customer/custom_field');

		$custom_fields = $this->model_customer_custom_field->getCustomFields(array('filter_customer_group_id' => $this->request->post['customer_group_id']));

		foreach ($custom_fields as $custom_field) {
			if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
				$this->error['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
			}
		}

		if ($this->request->post['password'] || (!isset($this->request->get['customer_id']))) {
			if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
				$this->error['password'] = $this->language->get('error_password');
			}

			if ($this->request->post['password'] != $this->request->post['confirm']) {
				$this->error['confirm'] = $this->language->get('error_confirm');
			}
		}

		if (isset($this->request->post['address'])) {
			foreach ($this->request->post['address'] as $key => $value) {
				if ((utf8_strlen($value['fullname']) < 1) || (utf8_strlen($value['fullname']) > 32)) {
					$this->error['address'][$key]['fullname'] = $this->language->get('error_fullname');
				}

				if ((utf8_strlen($value['shipping_telephone']) < 6) || (utf8_strlen($value['shipping_telephone']) > 20)) {
					$this->error['address'][$key]['shipping_telephone'] = $this->language->get('error_shipping_telephone');
				}

				if ((utf8_strlen($value['address']) < 3) || (utf8_strlen($value['address']) > 128)) {
					$this->error['address'][$key]['address'] = $this->language->get('error_address');
				}

				// if ((utf8_strlen($value['city']) < 2) || (utf8_strlen($value['city']) > 128)) {
				// 	$this->error['address'][$key]['city'] = $this->language->get('error_city');
				// }

				$this->load->model('localisation/country');

				$country_info = $this->model_localisation_country->getCountry($value['country_id']);

				if ($country_info && $country_info['postcode_required'] && (utf8_strlen($value['postcode']) < 2 || utf8_strlen($value['postcode']) > 10)) {
					$this->error['address'][$key]['postcode'] = $this->language->get('error_postcode');
				}

				if ($value['country_id'] == '') {
					$this->error['address'][$key]['country'] = $this->language->get('error_country');
				}

				if (!isset($value['zone_id']) || $value['zone_id'] == '') {
					$this->error['address'][$key]['zone'] = $this->language->get('error_zone');
				}

				if (!isset($value['city_id']) || $value['city_id'] == '') {
					$this->error['address'][$key]['city'] = $this->language->get('error_city');
				}

				foreach ($custom_fields as $custom_field) {
					if (($custom_field['location'] == 'address') && $custom_field['required'] && empty($value['custom_field'][$custom_field['custom_field_id']])) {
						$this->error['address'][$key]['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
					}
				}
			}
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	protected function validateApprove() {
		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	protected function validateUnlock() {
		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	public function login() {
		$json = array();

		if (isset($this->request->get['customer_id'])) {
			$customer_id = $this->request->get['customer_id'];
		} else {
			$customer_id = 0;
		}

		$this->load->model('customer/customer');

		$customer_info = $this->model_customer_customer->getCustomer($customer_id);

		if ($customer_info) {
			// Create token to login with
			$token = token(64);

			$this->model_customer_customer->editToken($customer_id, $token);

			if (isset($this->request->get['store_id'])) {
				$store_id = $this->request->get['store_id'];
			} else {
				$store_id = 0;
			}

			$this->load->model('setting/store');

			$store_info = $this->model_setting_store->getStore($store_id);

			if ($store_info) {
				$this->response->redirect($store_info['url'] . 'index.php?route=account/login&token=' . $token);
			} else {
				$this->response->redirect(HTTP_CATALOG . 'index.php?route=account/login&token=' . $token);
			}
		} else {
			$this->load->language('error/not_found');

			$this->document->setTitle($this->language->get('heading_title'));

			$data['heading_title'] = $this->language->get('heading_title');

			$data['text_not_found'] = $this->language->get('text_not_found');

			$data['breadcrumbs'] = array();

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('text_home'),
				'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['header'] = $this->load->controller('common/header');
			$data['column_left'] = $this->load->controller('common/column_left');
			$data['footer'] = $this->load->controller('common/footer');

			$this->response->setOutput($this->load->view('error/not_found.tpl', $data));
		}
	}

	public function history() {
		$this->load->language('customer/customer');

		$this->load->model('customer/customer');

		$data['text_no_results'] = $this->language->get('text_no_results');

		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_comment'] = $this->language->get('column_comment');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data['histories'] = array();

		$results = $this->model_customer_customer->getHistories($this->request->get['customer_id'], ($page - 1) * 10, 10);

		foreach ($results as $result) {
			$data['histories'][] = array(
				'comment'    => $result['comment'],
				'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}

		$history_total = $this->model_customer_customer->getTotalHistories($this->request->get['customer_id']);

		$pagination = new Pagination();
		$pagination->total = $history_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('customer/customer/history', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($history_total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($history_total - 10)) ? $history_total : ((($page - 1) * 10) + 10), $history_total, ceil($history_total / 10));

		$this->response->setOutput($this->load->view('customer/customer_history.tpl', $data));
	}

	public function addHistory() {
		$this->load->language('customer/customer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$this->load->model('customer/customer');

			$this->model_customer_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment']);

			$json['success'] = $this->language->get('text_success');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	//充值记录
	public function transaction() {

		$this->load->language('customer/customer');
		$this->load->model('customer/customer');

		$data['text_no_results'] = $this->language->get('text_no_results');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$start = ($page-1)*10;
		$limit = 10;

		$data['rechargeOrders'] = array();

		$results = $this->model_customer_customer->getRechargeOrder($this->request->get['customer_id']);
		$total = count($results);

		$data['rechargeOrders'] = array_slice($results,$start,$limit); //分页取数据

		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('customer/customer/transaction', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($total - 10)) ? $total : ((($page - 1) * 10) + 10), $total, ceil($total / 10));

		$this->response->setOutput($this->load->view('customer/customer_transaction.tpl', $data));
	}

	//定金记录
	public function depositOrder() {

		$this->load->language('customer/customer');
		$this->load->model('customer/customer');

		$data['text_no_results'] = $this->language->get('text_no_results');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$start = ($page-1)*10;
		$limit = 10;

		$data['depositOrders'] = array();

		$results = $this->model_customer_customer->getDepositOrder($this->request->get['customer_id']);
		$total = count($results);

		$data['depositOrders'] = array_slice($results,$start,$limit); //分页取数据

		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('customer/customer/depositOrders', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($total - 10)) ? $total : ((($page - 1) * 10) + 10), $total, ceil($total / 10));

		$this->response->setOutput($this->load->view('customer/customer_depositOrder.tpl', $data));
	}

	//余额订单记录
	public function tradeOrder() {

		$this->load->language('customer/customer');
		$this->load->model('customer/customer');

		$data['text_no_results'] = $this->language->get('text_no_results');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$start = ($page-1)*10;
		$limit = 10;

		$data['tradeOrders'] = array();

		$results = $this->model_customer_customer->getTradeOrder($this->request->get['customer_id']);
		$total = count($results);

		$data['tradeOrders'] = array_slice($results,$start,$limit); //分页取数据

		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('customer/customer/tradeOrder', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($total - 10)) ? $total : ((($page - 1) * 10) + 10), $total, ceil($total / 10));

		$this->response->setOutput($this->load->view('customer/customer_tradeOrder.tpl', $data));
	}

	//修改充值金额
	public function addTransaction() {

		$this->load->language('customer/customer');
		$this->load->model('customer/customer');

		$json = array();

		$old_balance = $this->model_customer_customer->getBalance($this->request->get['customer_id']);
		$data['money'] = $this->request->post['money'];
		$data['memo'] = $this->request->post['memo'];
		$data['type'] = $this->request->post['type'];

		//验证充值金额格式
		$money_reg = "/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/";

		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$json['error'] = $this->language->get('error_permission');
		}
		else if(!preg_match($money_reg, $data['money'])) {
			$json['error'] ="请正确填写金额数字";
		}
		else if($data['type'] == 0 && $old_balance-$data['money'] < 0){
			$json['error'] ="减少金额超出原有金额，请正确填写金额数字";
		}
		else if(trim($data['memo']) == ''){
			$json['error'] ="必须填写更改备注";
		}
		else{

			$this->model_customer_customer->addRechargeOrder($this->request->get['customer_id'], $data);

			$json['success'] = '成功：已修改用户金额';

		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	//修改定金
	public function addDeposit() {

		$this->load->language('customer/customer');
		$this->load->model('customer/customer');

		$json = array();

		$data['money'] = $this->request->post['money'];
		$data['memo'] = $this->request->post['memo'];

		//验证定金金额格式
		$money_reg = "/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/";

		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$json['error'] = $this->language->get('error_permission');
		}
		else if(!preg_match($money_reg, $data['money'])) {
			$json['error'] ="请正确填写定金金额数字";
		}
		else if(trim($data['memo']) == ''){
			$json['error'] ="必须填写定金备注";
		}
		else{

			$balance = $this->model_customer_customer->addDepositOrder($this->request->get['customer_id'], $data);

			$json['success'] = '成功：已修改用户定金';
			$json['balance'] = $balance;
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function reward() {
		$this->load->language('customer/customer');

		$this->load->model('customer/customer');

		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_balance'] = $this->language->get('text_balance');

		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_description'] = $this->language->get('column_description');
		$data['column_points'] = $this->language->get('column_points');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data['rewards'] = array();

		$results = $this->model_customer_customer->getRewards($this->request->get['customer_id'], ($page - 1) * 10, 10);

		foreach ($results as $result) {
			$data['rewards'][] = array(
				'points'      => $result['points'],
				'description' => $result['description'],
				'date_added'  => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}

		$data['balance'] = $this->model_customer_customer->getRewardTotal($this->request->get['customer_id']);

		$reward_total = $this->model_customer_customer->getTotalRewards($this->request->get['customer_id']);

		$pagination = new Pagination();
		$pagination->total = $reward_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('customer/customer/reward', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($reward_total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($reward_total - 10)) ? $reward_total : ((($page - 1) * 10) + 10), $reward_total, ceil($reward_total / 10));

		$this->response->setOutput($this->load->view('customer/customer_reward.tpl', $data));
	}

	public function addReward() {
		$this->load->language('customer/customer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'customer/customer')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$this->load->model('customer/customer');

			$this->model_customer_customer->addReward($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['points']);

			$json['success'] = $this->language->get('text_success');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function ip() {
		$this->load->language('customer/customer');

		$this->load->model('customer/customer');

		$data['text_no_results'] = $this->language->get('text_no_results');

		$data['column_ip'] = $this->language->get('column_ip');
		$data['column_total'] = $this->language->get('column_total');
		$data['column_date_added'] = $this->language->get('column_date_added');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data['ips'] = array();

		$results = $this->model_customer_customer->getIps($this->request->get['customer_id'], ($page - 1) * 10, 10);

		foreach ($results as $result) {
			$data['ips'][] = array(
				'ip'         => $result['ip'],
				'total'      => $this->model_customer_customer->getTotalCustomersByIp($result['ip']),
				'date_added' => date('d/m/y', strtotime($result['date_added'])),
				'filter_ip'  => $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . '&filter_ip=' . $result['ip'], 'SSL')
			);
		}

		$ip_total = $this->model_customer_customer->getTotalIps($this->request->get['customer_id']);

		$pagination = new Pagination();
		$pagination->total = $ip_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('customer/customer/ip', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($ip_total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($ip_total - 10)) ? $ip_total : ((($page - 1) * 10) + 10), $ip_total, ceil($ip_total / 10));

		$this->response->setOutput($this->load->view('customer/customer_ip.tpl', $data));
	}

	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_recommended_code']) ||isset($this->request->get['filter_company_name']) ||isset($this->request->get['filter_name']) || isset($this->request->get['filter_email']) || isset($this->request->get['filter_telephone'])) {
			if (isset($this->request->get['filter_name'])) {
				$filter_name = $this->request->get['filter_name'];
			} else {
				$filter_name = '';
			}

			if (isset($this->request->get['filter_email'])) {
				$filter_email = $this->request->get['filter_email'];
			} else {
				$filter_email = '';
			}

			if (isset($this->request->get['filter_recommended_code'])) {
				$filter_recommended_code = $this->request->get['filter_recommended_code'];
			} else {
				$filter_recommended_code = '';
			}

			if (isset($this->request->get['filter_company_name'])) {
				$filter_company_name = $this->request->get['filter_company_name'];
			} else {
				$filter_company_name = '';
			}

			if (isset($this->request->get['filter_telephone'])) {
				$filter_telephone = $this->request->get['filter_telephone'];
			} else {
				$filter_telephone = '';
			}
			if ($this->user->getLP()) {
				$filter_logcenter_id = $this->user->getLP();
			}

			$this->load->model('customer/customer');

			$filter_data = array(
				'filter_name'  => $filter_name,
				'filter_recommended_code'  => $filter_recommended_code,
				'filter_email' => $filter_email,
				'filter_company_name' => $filter_company_name,
				'filter_telephone' => $filter_telephone,
				'start'        => 0,
				'limit'        => 5
			);

			if (isset($filter_logcenter_id)) {
				$filter_data['filter_logcenter_id'] = $filter_logcenter_id;
			}

			$results = $this->model_customer_customer->getCustomers($filter_data);

			foreach ($results as $result) {
				$json[] = array(
					'recommended_code'	=> $result['recommended_code'],
					'customer_id'       => $result['customer_id'],
					'customer_group_id' => $result['customer_group_id'],
					'name'              => strip_tags(html_entity_decode($result['fullname'], ENT_QUOTES, 'UTF-8')),
					'customer_group'    => $result['customer_group'],
					'fullname'          => $result['fullname'],
					'email'             => $result['email'],
					'telephone'         => $result['telephone'],
					'company_name'         => $result['company_name'],
					'fax'               => $result['fax'],
					'custom_field'      => json_decode($result['custom_field'], true),
					'address'           => $this->model_customer_customer->getAddresses($result['customer_id'])
				);
			}
		}

		$sort_order = array();

		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function customfield() {
		$json = array();

		$this->load->model('customer/custom_field');

		// Customer Group
		if (isset($this->request->get['customer_group_id'])) {
			$customer_group_id = $this->request->get['customer_group_id'];
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}

		$custom_fields = $this->model_customer_custom_field->getCustomFields(array('filter_customer_group_id' => $customer_group_id));

		foreach ($custom_fields as $custom_field) {
			$json[] = array(
				'custom_field_id' => $custom_field['custom_field_id'],
				'required'        => empty($custom_field['required']) || $custom_field['required'] == 0 ? false : true
			);
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function address() {
		$json = array();

		if (!empty($this->request->get['address_id'])) {
			$this->load->model('customer/customer');

			$json = $this->model_customer_customer->getAddress($this->request->get['address_id']);
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
//导出excel表格
	public function export() {

		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_email'])) {
			$filter_email = $this->request->get['filter_email'];
		} else {
			$filter_email = null;
		}

		if (isset($this->request->get['filter_company_name'])) {
			$filter_company_name = $this->request->get['filter_company_name'];
		} else {
			$filter_company_name = null;
		}

		if (isset($this->request->get['filter_customer_group_id'])) {
			$filter_customer_group_id = $this->request->get['filter_customer_group_id'];
		} else {
			$filter_customer_group_id = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = null;
		}

		if (isset($this->request->get['filter_logcenter_id'])) {
			$filter_logcenter_id = $this->request->get['filter_logcenter_id'];
		} else {
			$filter_logcenter_id = null;
		}

		if (isset($this->request->get['filter_approved'])) {
			$filter_approved = $this->request->get['filter_approved'];
		} else {
			$filter_approved = null;
		}

		if (isset($this->request->get['filter_need_review'])) {
			$filter_need_review = $this->request->get['filter_need_review'];
		} else {
			$filter_need_review = null;
		}
		if (isset($this->request->get['filter_is_shelf_customer'])) {
			$filter_is_shelf_customer = $this->request->get['filter_is_shelf_customer'];
		} else {
			$filter_is_shelf_customer = null;
		}

		if (isset($this->request->get['filter_is_magfin'])) {
			$filter_is_magfin = $this->request->get['filter_is_magfin'];
		} else {
			$filter_is_magfin = null;
		}

		if (isset($this->request->get['filter_telephone'])) {
			$filter_telephone = $this->request->get['filter_telephone'];
		} else {
			$filter_telephone = null;
		}

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'name';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$filter_data = array(
			'filter_company_name'      => $filter_company_name,
			'filter_name'              => $filter_name,
			'filter_email'             => $filter_email,
			'filter_customer_group_id' => $filter_customer_group_id,
			'filter_status'            => $filter_status,
			'filter_logcenter_id'            => $filter_logcenter_id,
			'filter_approved'          => $filter_approved,
			'filter_need_review'          => $filter_need_review,
			'filter_is_shelf_customer'          => $filter_is_shelf_customer,
			'filter_is_magfin'          => $filter_is_magfin,
			'filter_date_start'        => $filter_date_start,
			'filter_date_end'        => $filter_date_end,
			'filter_telephone'                => $filter_telephone,
			'sort'                     => $sort,
			'order'                    => $order,
			'start'                    => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'                    => $this->config->get('config_limit_admin')
		);

		/*通过id获取物流中心中文*/
		$this->load->model('catalog/logcenter');
		$logcenters = $this->model_catalog_logcenter->getLogcenters($filter_data);
		$logcenters_dict = array();
		foreach ($logcenters as $logcenter) {
			$logcenters_dict[$logcenter['logcenter_id']] = $logcenter['logcenter_name'];
		}
		/*通过id获取物流中心中文*/

		/*通过id获取客户经理中文*/
		$logcenter_users = $this->model_catalog_logcenter->getUsers();
		$logcenter_users_dict = array();
		foreach ($logcenter_users as $logcenter_user) {
			$logcenter_users_dict[$logcenter_user['user_id']] = $logcenter_user['fullname'];
		}
		/*通过id获取客户经理中文*/

        /*
         * 获取所有客户的首单时间
         * @author sonicsjh
         */
        $this->load->model('sale/order');
        $firstOrderDate = $this->model_sale_order->getFirstOrderDateByCustomer();

		$country_dict = M('country')->getField('country_id,name');
		$zone_dict = M('zone')->getField('zone_id,name');
		$city_dict = M('city')->getField('city_id,name');

		//$shop_type_dict = array(4=>'区域正规大型连锁',5=>'1千平米以上单店及私人连锁',6=>'500平米-1000平米超市',7=>'500平米以下超市');
        $shop_type_dict = getShopTypes();

        $this->load->model('customer/customer');
		$results = $this->model_customer_customer->getExportCustomer($filter_data);

		// var_dump($results);die();
		$id = 1;

		foreach ($results as $key => $value) {
			$results[$key]['id'] = $id++;
			$results[$key]['first_check'] = '';
			$results[$key]['second_check'] = '';
			$results[$key]['address'] = $country_dict[$results[$key]['country_id']].$zone_dict[$results[$key]['zone_id']].$city_dict[$results[$key]['city_id']].$value['address'];
			$results[$key]['shop_type'] = $shop_type_dict[$results[$key]['shop_type']];
			$results[$key]['logcenter_name'] = $logcenters_dict[$results[$key]['logcenter_id']];
			$results[$key]['recommender'] = '';
			$results[$key]['manager1'] = $logcenter_users_dict[$results[$key]['user_id']];
			$results[$key]['manager2'] = '';
			if($results[$key]['is_shelf_customer']==0){
				$results[$key]['is_shelf_customer']="普通用户";
			}else{
				$results[$key]['is_shelf_customer']="货架客户";
			}
			$results[$key]['recommended_code'] = strval($results[$key]['recommended_code']);
			$results[$key]['comment'] = '';
            $results[$key]['firstOrderDate'] = $firstOrderDate[$value['customer_id']];
            /*
            if($firstOrderDate[$value['customer_id']]) {
                $results[$key]['firstOrderDate'] = date('Y年m月', strtotime($firstOrderDate[$value['customer_id']]));
            }
            */
		}
		//print_r($results);die;
		$this->load->library('PHPExcel/PHPExcel');
		$objPHPExcel = new PHPExcel();
		$objProps = $objPHPExcel->getProperties();
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");
		$objProps->setTitle("Think-tec Contact");
		$objProps->setSubject("Think-tec Contact Data");
		$objProps->setDescription("Think-tec Contact Data");
		$objProps->setKeywords("Think-tec Contact");
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);
		$objActSheet = $objPHPExcel->getActiveSheet();

		$objActSheet->setTitle('Sheet1');
		$col_idx = 'A';
		$headers = array('序号', '是否审核',	'日期', '初审',	 '二次审核', '注册电话', '公司名称', '姓名', '收货人', '收货人电话',	'收货地址','公司规模', '客户类型', '下单总数', '最近下单时间', '首单时间','物流营销中心', '业务员', '客户经理', 	'区域经理', '推荐码', '备注');
		$row_keys = array('id','need_review','date_added','first_check','second_check','telephone','company_name', 'fullname', 'a_fullname', 'shipping_telephone', 'address','shop_type','is_shelf_customer','order_sum','last_order_date','firstOrderDate','logcenter_name','recommender','manager1','manager2','recommended_code','comment');
		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);
		}
		//添加物流信息
		$i = 2;
		foreach ($results as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				// $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);
				$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Customers_'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
	}

	public function import() {
    $json = array();
    if (1) {
      if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
        // Sanitize the filename
        $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
        // Validate the filename length
        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
          $json['error'] = '文件名过短';
        }
        // Allowed file extension types
        $allowed = array('xls','xlsx');
        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
          $json['error'] = '请上传xls或者xlsx文件';
        }
        // Return any upload error
        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
          $json['error'] = '上传出现错误';
        }
      }
    }
    else {
      $json['error'] = '上传失败';
    }

    if (!$json) {
      $this->load->library('PHPExcel/PHPExcel');
      $savePath = $this->request->files['file']['tmp_name'];
      $PHPExcel = new PHPExcel();
      $PHPReader = new PHPExcel_Reader_Excel2007();
      if(!$PHPReader->canRead($savePath)){
        $PHPReader = new PHPExcel_Reader_Excel5();
      }
      $PHPExcel = $PHPReader->load($savePath);
      $currentSheet = $PHPExcel->getSheet(0);
      $allRow = $currentSheet->getHighestRow();
      //获取order_product_id, express_name, express_number在excel中的index
      $telephone_idx = $customer_name_idx = $recommend_name_idx = $recommend_code_idx = 0;
      $tmp_idx = 'A'; //假设导入表格不会长于Z
      $currentRow = 1;
      while(($telephone_idx === 0 || $customer_name_idx === 0 || $recommend_name_idx === 0 || $recommend_code_idx === 0)&&$tmp_idx<'Z') {
        switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
          case '会员手机号':
            $telephone_idx = $tmp_idx;
            break;
          case '会员名':
            $customer_name_idx = $tmp_idx;
            break;
          case '业务员姓名':
            $recommend_name_idx = $tmp_idx;
            break;
          case '推荐码':
            $recommend_code_idx = $tmp_idx;
            break;
        }
        $tmp_idx++;
      }

      if(0 === $telephone_idx || 0 === $customer_name_idx||0 === $recommend_name_idx||0 === $recommend_code_idx) {
        $json['error'] = '请检查文件第一行是否有：会员手机号、会员名、业务员姓名、推荐码';
      }

      if (!$json) {
        $this->load->model('customer/customer');
        $customers_info = array();
        for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
          $telephone = (String)$currentSheet->getCell($telephone_idx.$currentRow)->getValue();
          $customer_name = (String)$currentSheet->getCell($customer_name_idx.$currentRow)->getValue();
          $recommend_name = (String)$currentSheet->getCell($recommend_name_idx.$currentRow)->getValue();
          $recommend_code = (String)$currentSheet->getCell($recommend_code_idx.$currentRow)->getValue();
          //检查会员是否存在
          $customer = M('customer')->where('telephone='.$telephone)->find();
          // var_dump($product);
          if(empty($customer)) {
            $json['error'] = '第' . $currentRow . '会员未找到';
          }

           //检查此业务员是否存在
          $map['fullname'] = array('like','%'.$recommend_name.'%');
          $recommend_user_id = M('user')->where($map)->getField('user_id');

	      if(empty($recommend_user_id)) {
	      	$json['error'] = '第' . $currentRow . '业务员未找到';
	      }


          if(isset($json['error'])) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
            return;
          }
          $customer_data = array(
          	'telephone' => $telephone,
          	'recommend_name'=> $recommend_name,
          	'recommend_code'=> $recommend_code,
          	'recommend_user_id'=> $recommend_user_id?$recommend_user_id:0,
          	);
          $customers_info[] = $customer_data;
        }
        $this->load->model('customer/customer');
        foreach ($customers_info as $key => $value) {
        	$this->model_customer_customer->updateRecommendCodeByTelephone($value);
        }
      }

      if (!isset($json['error'])) {
        $json['success'] = sprintf('更新 %s条记录', count($customers_info));
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));

  }

	//添加新用户优惠券
	public function addNewCoupon($customer_id){

		//因为优惠包括当天所以天数要减1天
		$this->createCoupon($customer_id,'新用户注册',20,0,59,1); //20优惠券1张2月
		$this->createCoupon($customer_id,'新用户注册',30,0,59,1); //30优惠券1张2月
		$this->createCoupon($customer_id,'新用户注册',50,500,13,1); //50优惠券1张2周

		$this->load->model('marketing/coupon');
		$this->model_marketing_coupon->setCouponStatus($customer_id); //设置发送完毕后状态

		$appId = '356090190000250362';
		$appSecret = '386d5615c7a6d9215e23f13384947599';
		$templateId = '91552880';
		$phone = trim($this->request->post['telephone']);
		$template_param = json_encode(array(
			'day'=>'14'
		));
		$sms = new ControllerRestSms;
		$resms = $sms->sendSms($appId, $appSecret, $templateId, $phone, $template_param);

		if($resms == 'successful'){
		}
		else{
			$json ['error']['warning'] = $resms;
		}

	}

	//产生优惠券
	public function createCoupon($customer_id,$name,$price,$total,$days,$number) {
		$this->load->model('marketing/coupon');
		$data['name'] = $name;
		$data['type'] = 'F';
		$data['discount'] = $price;
		$data['total'] = $total;
		$data['logged'] = 1;
		$data['shipping'] = 0;
		$data['date_start'] = date('Y-m-d H:i:s');
		$data['date_end'] = date('Y-m-d H:i:s', time()+3600*24*$days);
		$data['uses_total'] = 1;
		$data['uses_customer'] = 1;
		$data['status'] = 1;
		$data['number'] = $number;
		$this->model_marketing_coupon->addCouponToCustomer($customer_id, $data);
	}
//统计2017年每月用户订单信息
	public function statistics(){
		
					$this->load->model('customer/customer');
					$customer_ids=$this->model_customer_customer->getcustomer_id();
					$customerid=array_column($customer_ids, 'customer_id');
					$results = $this->model_customer_customer->getExporstatistics($customerid);
					//print_r($results);die;
					//导出excel表格
					$this->load->library('PHPExcel/PHPExcel');
					$objPHPExcel = new PHPExcel();
					$objProps = $objPHPExcel->getProperties();
					$objProps->setCreator("Think-tec");
					$objProps->setLastModifiedBy("Think-tec");
					$objProps->setTitle("Think-tec Contact");
					$objProps->setSubject("Think-tec Contact Data");
					$objProps->setDescription("Think-tec Contact Data");
					$objProps->setKeywords("Think-tec Contact");
					$objProps->setCategory("Think-tec");
					$objPHPExcel->setActiveSheetIndex(0);
					$objActSheet = $objPHPExcel->getActiveSheet();

					$objActSheet->setTitle('Sheet1');
					$col_idx = 'A';
					foreach ($results as $key => $value) {
								$headers = $value;
					}

					foreach ($headers as $key => $value) {
								$head[]=$key;
					}

					foreach ($headers as $key => $value) {
								$row_keys[]=$key;
					}
					//var_dump($head);die;

					foreach ($head as $header) {
						$objActSheet->setCellValue($col_idx++.'1', $header);
					}

					$i = 2;
					foreach ($results as $rlst) {
						$col_idx = 'A';
						foreach ($row_keys as $rk) {
						  $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);
						}
						$i++;
					}

					$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

					ob_end_clean();
					// Redirect output to a client’s web browser (Excel2007)
					header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
					header('Content-Disposition: attachment;filename="Customers_'.date('Y-m-d',time()).'.xlsx"');
					header('Cache-Control: max-age=0');
					// If you're serving to IE 9, then the following may be needed
					header('Cache-Control: max-age=1');

					// If you're serving to IE over SSL, then the following may be needed
					header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
					header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
					header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
					header ('Pragma: public'); // HTTP/1.0
			    $objWriter->save('php://output');
			    exit;
	}

		//导入excel修改推荐码
	public function importcode() {

    $json = array();
    if (1) {
      if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
        // Sanitize the filename
	        $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
	        // Validate the filename length

	        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
	          $json['error'] = '文件名过短';
	        }
	        // Allowed file extension types
	        $allowed = array('xls','xlsx');
	        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
	          $json['error'] = '请上传xls或者xlsx文件';
	        }
	        // Return any upload error
	        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
	          $json['error'] = '上传出现错误';
	        }
      }
    } else {
      $json['error'] = '上传失败';
    }

    if (!$json) {
      $this->load->library('PHPExcel/PHPExcel');
      $savePath = $this->request->files['file']['tmp_name'];
      $PHPExcel = new PHPExcel();
      $PHPReader = new PHPExcel_Reader_Excel2007();
		      if(!$PHPReader->canRead($savePath)){
		        $PHPReader = new PHPExcel_Reader_Excel5();
		      }

		      $PHPExcel = $PHPReader->load($savePath);
		      //var_dump($PHPExcel);die;
		      $currentSheet = $PHPExcel->getSheet(0);
		      $allRow = $currentSheet->getHighestRow();
		      // var_dump($allRow);die;
		      //获取order_product_id, express_name, express_number在excel中的index
		      $sku_idx = $option_name_idx = $qty_idx = 0;
		      $tmp_idx = 'A'; //假设导入表格不会长于Z
		      $currentRow = 1;
		      // var_dump($currentSheet->getCell($tmp_idx.$currentRow)->getValue());
		      while(($tmp_idx === 0 || $option_name_idx === 0 || $qty_idx === 0)&&$tmp_idx<'Z') {
		        switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
		          case '手机号':
		            $sku_idx = $tmp_idx;
		            break;
		          case '业务员':
		            $option_name_idx = $tmp_idx;
		            break;
		          case '推荐码':
		            $qty_idx = $tmp_idx;
		            break;
		        }
		        $tmp_idx++;
		      }

		      if(0 === $sku_idx || 0 === $option_name_idx||0 === $qty_idx) {
		        $json['error'] = '请检查文件第一行是否有：手机号、业务员、推荐码';
		      }

		      if (!$json) {

				        for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
				          $sku = (String)$currentSheet->getCell($sku_idx.$currentRow)->getValue();
				          $option_name = (String)$currentSheet->getCell($option_name_idx.$currentRow)->getValue();
				          $qty = (String)$currentSheet->getCell($qty_idx.$currentRow)->getValue();

				          $customer_data[] = array(
				            'telephone' => $sku,
				            'recommend_name'=> $option_name,
				            'recommend_code'=> $qty,
				            );

			          if(isset($json['error'])) {
			            $this->response->addHeader('Content-Type: application/json');
			            $this->response->setOutput(json_encode($json));
			            return;
			          }


		        }


      }
      //var_dump($customer_data);die;
		      foreach ($customer_data as $key => $value) {
		     	 $user_id=$this->db->query("select user_id from user where recommended_code=".$value['recommend_code'])->row;

		      	$this->db->query("update customer set user_id=".$user_id['user_id'].",recommended_code=".$value['recommend_code']."  where fullname=".$value['telephone']);
		      }

		    $this->response->addHeader('Content-Type: application/json');
		    $this->response->setOutput(json_encode($json));


  		}
}

}
